<?php

namespace app\admin\controller\shop\task;

use app\common\controller\Backend;
use think\Db;

/**
 * 任务管理
 *
 * @icon fa fa-circle-o
 */
class Lists extends Backend
{

    /**
     * Task模型对象
     * @var \app\common\model\shop\Task
     */
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'task_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\shop\Task;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //
            $join[] = ['shop s', 's.shop_id = t.shop_id'];
            $field  = "t.task_id,t.goods_sno,t.task_sno,s.shop_name,t.create_time,t.service_change_price,t.task_status";
            $total  = $this->model->alias('t')->join($join)->field($field)->where($where)->count();
            $list   = $this->model->with('taskKey')->alias('t')->join($join)->field($field)->where($where)->limit($offset, $limit)->select();
            foreach ($list as $key => $value) {
                $keyword = $value->task_key;
                foreach ($keyword as $k => $v) {
                    $arr[] .= $v->key_word;
                }
                $value['task_status'] = $value['task_status'] == 1 ? '未发布' : '已发布';
                if (count($arr) > 0) {
                    $value['key_word'] = implode(',', $arr);
                }
                unset($arr);
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {

            $params                = $this->request->post('row/a');
            $params['create_time'] = time();
            $params['update_time'] = time();
            $params['limit_price'] = $params['down'] . ',' . $params['up'];
            if ($params['type'] == 'draft') {
                $params['task_status'] = 1;
            }
            if ($params['type'] == 'send') {
                $params['task_status'] = 2;
            }
            //流量单无需好评、追评、晒图、发货
            if ($params['task_type'] == 3) {
                $params['is_good_evalute']      = 2;
                $params['is_review']            = 2;
                $params['is_review_slide_show'] = 2;
                $params['is_need_send']         = 2;
            }
            $params['shop_admin_id'] = session('admin')['id'];
            if ($params['key_word']) {
                foreach ($params['key_word'] as $key => $value) {
                    if (empty($value) || empty($params['task_num'][$key])) {
                        return json(['code' => 0, 'msg' => '任务关键字或者任务数量不能为空']);
                    }
                }
            }
            $total_num = 0;
            $validate  = \think\Loader::validate('shop.Lists');
            \think\Db::startTrans();
            try {
                $key_word = $params['key_word'];
                $task_num = $params['task_num'];
                foreach ($task_num as $key => $value) {
                    $total_num += (int) $value;
                }
                //判断钱包   余额是否足够
                $wallet    = Db::name('shop_admin_wallet')->where('admin_id', session('admin')['id'])->find();
                $shop_gold = Db::name('shop')->where('shop_id', $params['shop_id'])->where('status', 1)->value('gold_bean');
                // if(empty($shop_gold)){

                // }
                if (empty($wallet)) {
                    return json(['code' => 0, 'msg' => '钱包余额不足']);
                }
                $ward_good_evalute = 0;
                $ward_review       = 0;
                //只有 精刷单以及 隔日单  有涉及到好评 跟追评
                if (in_array($params['task_type'], [1, 2])) {
                    if ($params['is_good_evalute'] == 1) {
                        $ward_good_evalute = $total_num;
                    }
                    if ($params['is_review'] == 1) {
                        $ward_review = $total_num;
                    }
                }
                //计算 任务需要的总 金豆数 = 每单金豆数 * 任务总数 + 好评奖励 + 追评奖励  （好评奖励、追评奖励 默认每单 一个金豆）
                $total_gold = ((int)($shop_gold * $total_num) + (int)$ward_review + (int)$ward_good_evalute);
                // dump($params['shop_id']);
                // dump($total_gold);
                // dump($total_num);
                // dump($wallet['balance']);die;
                if ($total_gold > $wallet['balance']) {
                    return json(['code' => 0, 'msg' => '账户余额不足，不可发布任务']);
                }
                //钱包余额减少
                $dec = Db::name('shop_admin_wallet')->where('admin_id', session('admin')['id'])->setDec('balance', $total_gold);


                if ($params['send']) {
                    $params['send_time'] = time();
                }
                $params['total_task_num'] = $total_num;
                $params['left_task_num']  = $total_num;
                $params['price_limit']    = $params['limit_price'];
                unset($params['down']);
                unset($params['up']);
                unset($params['key_word']);
                unset($params['task_num']);
                unset($params['type']);
                unset($params['limit_price']);
                $params['task_sno'] = get_only_order_no();
                $limit_task_num     = \app\common\model\Shop::where('shop_id', $params['shop_id'])->value('left_num');
                $res                = 1;
                if ($params['task_type'] == 1 && $total_num > $limit_task_num) {
                    return json(['code' => 0, 'msg' => '精刷单不能超过任务限制数' . $limit_task_num]);
                    $res = \app\common\model\Shop::where('shop_id', $params['shop_id'])->setDec('left_num', $total_num);
                }
                $result = $this->model->validate('shop.Lists')->create($params);
                if ($result === false) {
                    return json(['code' => 0, 'msg' => $this->model->getError()]);
                }
                foreach ($key_word as $key => $value) {
                    $arr[] = [
                        'task_id'  => $result->task_id,
                        'key_word' => $value,
                        'send_num' => $task_num[$key],
                        'left_num' => $task_num[$key],
                        'order_amount'=>(floatval($total_gold)/intval($total_num))*intval($task_num[$key]),
                        'left_task_num_one'=>$task_num[$key],
                        'left_task_num_tow'=>0,
                    ];
                }
                //添加流水记录
                $finance = \app\common\model\Finance::create([
                    'shop_admin_id' => session('admin')['id'],
                    'on_time'       => time(),
                    'remark'        => '发布任务暂扣商户余额',
                    'source'        => 'shop',
                    'fina_channel'  => 1,
                    'fina_cash'     => $total_gold,
                    'balance'       => Db::name('shop_admin_wallet')->where('admin_id', session('admin')['id'])->value('balance'),
                    'desc'          => '发布' . $total_num . '个任务,扣除' . $total_gold . '金币,其中任务' . $shop_gold * $total_num . ',好评' . $ward_good_evalute . ',追评' . $ward_review,
                    'obj_id'        => $result->task_id,//任务id
                ]);

                //添加冻结的钱
                Db::name("shop_admin_wallet")->where("admin_id",session('admin')['id'])->setInc("frozen_money",$total_gold);

                $task = model('shop.task.Key')->saveAll($arr);
                if ($result && $task !== false && $dec !== false && $finance !== false && $res !== false) {
                    \think\Db::commit();
                    if ($params['draft']) {
                        return json(['code' => 1, 'msg' => '任务保存成功']);
                    } else {
                        return json(['code' => 1, 'msg' => '任务发布成功']);
                    }

                } else {
                    \think\Db::rollback();
                    if ($params['draft']) {
                        return json(['code' => 0, 'msg' => '任务保存失败']);
                    } else {
                        return json(['code' => 0, 'msg' => '任务发布失败']);
                    }
                }
            } catch (Exception $e) {
                \think\Db::rollback();
                if ($params['draft']) {
                    return json(['code' => 0, 'msg' => '任务保存失败']);
                } else {
                    return json(['code' => 0, 'msg' => '任务发布失败']);
                }
            }
        }
        $shop = Db::name('shop')->where(['shop_admin_id' => session('admin')['id']])->where('status', 1)->select();
        $this->view->assign('shop', $shop);
        return $this->view->fetch();
    }

    public function update_status($ids = '')
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $sendIds = $this->request->post('ids/a');
                foreach ($sendIds as $key => $value) {
                    $id[] = $value['task_id'];
                }
                unset($value);
            } else {
                $id = $params['ids'];
            }
            $row = $this->model->where('task_id', 'in', $id)->where('task_status', 1)->select();
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            try {
                $this->model->where('task_id', 'in', $ids)->update(['task_status' => 2, 'send_time' => time()]);
                return json(['code' => 1, 'msg' => '发布成功']);
            } catch (Exception $e) {
                return json(['code' => 0, 'msg' => '发布失败']);
            }

        } else {
            return json(['code' => 0, 'msg' => '发布失败']);
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $taskList = $this->model->where('task_id', 'in', $ids)->select();
            if ($taskList) {
                $deleteIds = [];
                foreach ($taskList as $k => $v) {
                    if ($v->task_status == 2 && $v->total_task_num == $v->left_task_num) {
                        $deleteIds[] = $v->task_id;
                    }
                }
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    $this->success();
                }
            }
        }
        $this->error();
    }

    public function getShop()
    {
        $shop_type = input('post.shop_type');
        if (empty($shop_type)) {
            return json(['code' => 0, 'msg' => '请选择店铺类型']);
        }
        if ($shop_type == 3) {
            $where['shop_type'] = ['in', [0, 1, 2]];
        } else {
            $where['shop_type'] = $shop_type;
        }
        $shop = Db::name('shop')->where(['shop_admin_id' => session('admin')['id'], 'status' => 1])->where($where)->select();
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $shop]);
    }

}
